<template>
  <div class="loginWapper">
    <!-- <HeadNav
      :title="'设置密码'"
      :left-arrow="true" ></HeadNav> -->
    <div class="container">
      <div class="content">
        <van-form
          @submit="submitEdit"
          ref="form">
          <input
            type="text"
            id="username"
            name="username"
            hidden
            autocomplete="username">
          <div class="fieldBox">
            <van-cell-group :border="false">
              <div class="passWordInfoItem">
                <div class="item_label">原密码</div>
                <van-field
                  class="inputText"
                  :type="passwordVisible.oldPassWord ? 'text' : 'password'"
                  v-model="userInfo.oldPassWord"
                  clearable
                  placeholder="请输入原密码"
                  :right-icon="passwordVisible.oldPassWord ? 'eye-o' : 'closed-eye'"
                  @click-right-icon="togglePasswordVisibility(0, 'oldPassWord')"
                  :right-icon-style="{ fontSize: '20px', color: '#1989fa' }"
                  :rules="passwordRules.oldPassWord"
                  autocomplete="current-password"/>
              </div>
              <div class="passWordInfoItem mt25">
                <div class="item_label">新密码</div>
                <van-field
                  class="inputText"
                  :type="passwordVisible.newPassWord ? 'text' : 'password'"
                  v-model="userInfo.newPassWord"
                  clearable
                  placeholder="请输入8-16位密码"
                  :right-icon="passwordVisible.newPassWord ? 'eye-o' : 'closed-eye'"
                  @click-right-icon="togglePasswordVisibility(1, 'newPassWord')"
                  :rules="passwordRules.newPassWord"
                  autocomplete="new-password"/>
              </div>
              <div class="passWordInfoItem mt25">
                <div class="item_label">确认密码</div>
                <van-field
                  class="inputText"
                  :type="passwordVisible.againPassWord ? 'text' : 'password'"
                  v-model="userInfo.againPassWord"
                  clearable
                  placeholder="请输入8-16位确认密码"
                  :right-icon="passwordVisible.againPassWord ? 'eye-o' : 'closed-eye'"
                  @click-right-icon="togglePasswordVisibility(2, 'againPassWord')"
                  :rules="passwordRules.againPassWord"
                  autocomplete="new-password"/>
              </div>
              <div class="passWordTips">密码必须是8-16位的英文字母、数字组合（不能是纯数字）</div>
            </van-cell-group>
          </div>

          <div class="btnArea">
            <van-button
              type="primary"
              class="loginBtn"
              native-type="submit">确认修改 </van-button>
            <!-- <van-button type="primary" class="loginBtn" @click="submitEdit()">确认修改 </van-button> -->
          </div>
        </van-form>
      </div>
    </div>
    <!-- <foot></foot> -->
  </div>
</template>
<script>
/* eslint-disable */
// import HeadNavSecond from '@/components/HeadNavSecond'
import { loginApi,resetPwdApi } from '@/api/api';
import { Toast } from 'vant';
import HeadNav from '@/components/HeadNav'

//import foot from '../foot/foot.vue'
export default {
  name: 'PassWord',
  components: { HeadNav },
  data() {
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/;
    const commonRules = [
      { required: true, message: '请输入8-16位密码' },
      // { pattern: passwordRegex, message: '密码必须是8-16位的英文字母、数字组合（不能是纯数字）' }
    ];
    return {
      show: true,
      userInfo: {
        oldPassWord: undefined,
        newPassWord: undefined,
        againPassWord: undefined,
      },
      userType: '',
      isPasswordVisible: [false, false, false],// 控制密码是否可见
      passwordVisible:{
        oldPassWord:false,
        newPassWord: false,
        againPassWord: false,
      },
      passwordRules: {
        oldPassWord: [{ required: true, message: '请输入8-16位密码' }],
        newPassWord: [...commonRules],
        againPassWord: [
          ...commonRules,
          // { required: true, message: '请输入8-16位确认密码' },
          // { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/, message: '密码必须是8-16位的英文字母、数字组合（不能是纯数字）' },
          {
            validator: (value) => {
              return value === this.userInfo.newPassWord;
            },
            message: '新密码和确认密码不一致'
          }
        ]
      },
      formValidated: {
        oldPassWord: false,
        newPassWord: false,
        againPassWord: false
      }
    }
  },
  watch: {
    isPasswordVisible: {
      deep: true,
      handler(newVal) {
        console.log('isPasswordVisible 更新为', newVal);
      }
    }
  },
  mounted() {
    document.title = '修改密码'
  },
  created() {
    // sessionStorage.setItem('tabIndex', '')
  },

  methods: {
    // 切换密码可见性
    togglePasswordVisibility(index,fileName) {
      console.log(index, 'dianji', this.isPasswordVisible[index])
      this.isPasswordVisible[index] = !this.isPasswordVisible[index]
      this.passwordVisible[fileName]= !this.passwordVisible[fileName]
    },
    changeRouterGo() {
      console.log('返回主页')
      // this.$router.push({ path: '/index' })
    },
    handleBackGo() {
      // this.$router.go(-1)
      this.$router.push({ path: '/mine' })
    },
    validator(val) {
      // 先检查 val 是否为空或者未定义
      if (val === null || val === undefined || val.trim() === '') {
        return false;
      }
      // 再进行正则表达式校验
      return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/.test(val);
    },
    validator1(val) {
      return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/.test(val);
    },
    // 确认修改密码
    submitEdit() {
      const { oldPassWord, newPassWord, againPassWord } = this.userInfo;

      // 验证密码格式
      const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/;
      if (!passwordRegex.test(newPassWord)) {
        Toast('设置的密码必须是8-16位的英文字母、数字组合');
        return;
      }

      // 验证确认密码是否匹配
      if (newPassWord !== againPassWord) {
        Toast('新密码和确认密码不一致');
        return;
      }
      // // 验证通过，更新验证状态
      // this.formValidated = {
      //   oldPassWord: true,
      //   newPassWord: true,
      //   againPassWord: true
      // };
      // 验证表单字段
      this.$refs.form.validate().then(() => {
        // 验证通过，提交修改密码请求
        // 这里需要根据实际的接口进行修改
        // 示例代码中假设存在一个 changePasswordApi 接口
        if (newPassWord) {
            resetPwdApi({oldPassword:oldPassWord, password: newPassWord }).then(res => {
                if (res.code === 200) {
                    Toast('修改密码成功！')
                    this.$router.push({
                      path:'/login'
                    })
                }else{
                  Toast(res.message);
                }
                console.log(res, 'res')
            })
          }
        // changePasswordApi({ oldPassWord, newPassWord }).then(res => {
        //   if (res.code === 200) {
        //     Toast('密码修改成功');
        //     // 可以在这里进行页面跳转等操作
        //   } else {
        //     Toast(res.message);
        //   }
        // }).catch(error => {
        //   console.error('修改密码失败:', error);
        //   Toast('修改密码失败，请稍后重试');
        // });
        console.log('提交修改密码请求:', { oldPassWord, newPassWord });
        // Toast('模拟提交修改密码请求');
      }).catch(errors => {
        // 验证失败，更新验证状态
        this.formValidated = {
          oldPassWord: false,
          newPassWord: false,
          againPassWord: false
        };
        // 验证失败，显示错误信息
        const errorMessages = errors.map(error => error.message);
        Toast(errorMessages.join('\n'));
      });
    },
  }
}
</script>

<style lang="less" scoped>
.loginWapper {
  // background: url(../../assets/images/loginBg.png) no-repeat;
  background-size: 100%;
  background-color: white;
}

.container {
  background-size: 100%;
}

.content {
  // margin-top: 35px;
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 2px);
  background: transparent;
}

.icon-box {
 // margin-top: 55px;
  text-align: center;
  margin-bottom: 59px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

img {
  width: 72px;
  height: 72px;
  margin-top: 36px;
  margin-bottom: 11px;
}

.icon-box-text {
  // width: 64px;
  height: 22px;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: bold;
  color: #333333;
  // line-height: 22px;
}

.passWordInfoItem {
  background: transparent;
  display: flex;
  flex-direction: column;

  .item_label {
    font-size: 14px;
    color: #000000;
    text-align: left;
  }
}






.fieldBox {
  padding: 0px 30px;
  text-align: center;
  margin-top: 24px;

  .inputText {
    margin-top: 16px;
    border-radius: 10px;
    background: #f9f9f9;
  }

  .passWordTips {
    font-size: 12px;
    text-align: left;
    color: #000000;
    margin-top: 17px;
  }

  /deep/.van-cell-group {
    background: transparent;
  }

  /deep/.van-cell {
    display: flex;
    align-items: center;
    min-height: 40px;
  }

  /deep/.van-field__control {
    font-size: 12px;
    line-height: 12px;
    text-align: left;
    color: #999999;
  }


}
/deep/.van-field--error .van-field__control, .van-field--error .van-field__control::placeholder{
  color: #999999 !important;
  -webkit-text-fill-color: #999999 !important;
}


.btnArea {
  padding: 0px 30px;
  margin-top: 108px;
}

.loginBtn {
  width: 100%;
  height: 45px;
  border: none;
  background: #047DCB;
  border-radius: 45px;
  margin-bottom: 20px;
}

.mt25 {
  margin-top: 25px;
}
</style>